package com.yilin.platform.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.platform.base_core.application.AppUtil;
import com.yilin.platform.base_core.application.PageData;
import com.yilin.platform.base_core.commons.exception.BusinessException;
import com.yilin.platform.base_core.commons.utils.ArrayUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.base_core.tools.QueryUtil;
import com.yilin.platform.entity.enums.user.OrganType;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.entity.user.Organize;
import com.yilin.platform.entity.user.auth.BusinessLicense;
import com.yilin.platform.entity.user.auth.TransBusinessLicense;
import com.yilin.platform.mapper.user.AccountMapper;
import com.yilin.platform.mapper.user.OrganizeMapper;
import com.yilin.platform.service.user.IOrganizeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrganizeService extends ServiceImpl<OrganizeMapper, Organize> implements IOrganizeService {

    @Resource
    private  OrganizeMapper organizeMapper;
    @Resource
    private  AccountService accountService;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AuthService authService;
    /**
     * 客户注册通道
     */
    @Override
    public void organizeRegister(Organize organize, Account account) {
        QueryWrapper<Organize> queryWrapper;
        /// ### 检查组织名称
        if (StringUtil.isNotEmpty(organize.getOrganizeName())&&organize.getOrganType()!= OrganType.individual) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("organize_name", organize.getOrganizeName());
            if (organizeMapper.selectOne(queryWrapper) != null) {
                throw new BusinessException("注册的组织信息已存在，不要重复注册！");
            }
        }
        /// ### 检查账户信息是否存在
        Account extAccount = accountService.getAccountByUsername(account.getUsername());
        if (extAccount != null) throw new BusinessException("注册的账号已存在，不要重复注册！");
        Account pheAccount = accountService.getAccountByPhone(account.getPhone(), account.getUserType());
        if (pheAccount != null) throw new BusinessException("该手机号已被注册！请直接登录或更换手机号");
        // ### 如果存在手机号相同的已删除账号，采用账户覆盖，不重新建立账户，部分信息，如认证功能会得到恢复
        List<Account> phoneAccList = accountService.getLogicAccountByPhone(account.getPhone());
        if (phoneAccList.size() > 0) {
            account.setId(ArrayUtil.first(phoneAccList).getId());
            accountMapper.recoveryById(account.getId());
        }
        organize.setCreateTime(new Date());
        organize.setOrganizeTel(account.getPhone());
        organizeMapper.insert(organize);
        //组织创建成功，初始化角色
        account.setOrganizeId(organize.getId());
        account.setOrganizeName(organize.getOrganizeName());
        account.setRoleName("组织管理员");
        account.setUserState(Account.UserState.enable);
        account.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
        account.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
        //密码MD5加密
        account.setPassword(AppUtil.md5(account.getPassword()));
        if (account.getId()==null) accountMapper.insert(account);
        else accountMapper.updateById(account);

        organize.setManagerUserId(account.getId());
        organize.setManagerUserName(account.getName());
        organize.setManagerUserPhone(account.getPhone());
        organizeMapper.updateById(organize);

        //设置自己为管理员
        account.setOrganizeManagerUserId(account.getId());
        account.setOrganizeManagerUserName(account.getName());
        accountMapper.updateById(account);
    }

    /**
     * 找查 组织ID
     */
    @Override
    public Organize getOrganizeById(String organizeId) {;
        return organizeMapper.selectById(organizeId);
    }

    @Override
    public List<Organize> getGroupOrganizeList(String groupOrganizeId) {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("superior_plat_organize_id", groupOrganizeId);
        return organizeMapper.selectList(queryWrapper);
    }
    @Override
    public PageData<Organize> getBelowOrganizePage(String organizeId, Organize query, Integer page, Integer limit) {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("superior_plat_organize_id", organizeId);
        queryWrapper.ne("id",organizeId);
        return organizeMapper.selectPage(new PageData<>(page,limit), queryWrapper);
    }
    @Override
    public PageData<Organize> getAuthorizedOrganizePage(Organize query, Integer page, Integer limit) {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authorized", true);
        QueryUtil.andQueryWrapper(queryWrapper, query);
        return organizeMapper.selectPage(new PageData<>(page, limit), queryWrapper);
    }
    /**
     * 获取直下级平台公司分页
     * 这里获取的是运营平台 向下一级平台
     */
    @Override
    public PageData<Organize> getLowerOrganizePage(Organize query, Integer page, Integer limit) {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("superior_plat_organize_id", query.getId());
        queryWrapper.ne("user_type", UserType.shipperUser).ne("user_type", UserType.truckerUser);
        QueryUtil.andQueryWrapper(queryWrapper, query);
        return organizeMapper.selectPage(new PageData<>(page, limit), queryWrapper);
    }
    @Override
    public List<Organize> getOrganizeListByIds(String[] organizeIds) {
        return organizeMapper.selectBatchIds(ArrayUtil.initList(organizeIds));
    }
    @Override
    public void updateOrganize(Account loginUser, Organize organize, Organize localOrganize) {
        if (organize.getOrganizeName() != null) localOrganize.setOrganizeName(organize.getOrganizeName());
        if (organize.getOrganizeLogo() != null) localOrganize.setOrganizeLogo(organize.getOrganizeLogo());
        if (organize.getOrganizeTel() != null) localOrganize.setOrganizeTel(organize.getOrganizeTel());
        if (organize.getSignatureImg() != null) localOrganize.setSignatureImg(organize.getSignatureImg());
        if (organize.getIntroduction() != null) localOrganize.setIntroduction(organize.getIntroduction());
        if (organize.getLegalName() != null) localOrganize.setLegalName(organize.getLegalName());
        if (organize.getLegalPhone() != null) localOrganize.setLegalPhone(organize.getLegalPhone());
        if (organize.getAddress() != null) localOrganize.setAddress(organize.getAddress());
        localOrganize.setUpdateTime(new Date());
        localOrganize.setUpdateUserId(loginUser.getId());
        organizeMapper.updateById(localOrganize);
        //批量修改相同组织下的用户组织基本信息
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organize_id", localOrganize.getId());
        List<Account> accountList = accountMapper.selectList(queryWrapper);
        for (Account account : accountList) {
            account.setOrganizeName(localOrganize.getOrganizeName());
            account.setOrganType(localOrganize.getOrganType());
            account.setOrganizeLogo(localOrganize.getOrganizeLogo());
            accountMapper.updateById(account);
        }
    }
    /**
     * 解散组织
     */
    @Override
    public void dismissOrganize(Account loginUser, Organize organize) {
        List<Account> employeeList = accountService.getEmployeeByOrganizeId(organize.getId());
        for (Account account : employeeList) accountService.scrapAccount(loginUser, account);
        BusinessLicense businessLicense = authService.getBusinessLicenseByOrganizeId(organize.getId());
        if (businessLicense != null) authService.deleteBusinessLicenseById(businessLicense);
        TransBusinessLicense transBusinessLicense = authService.getTransLicenseByOrganizeId(organize.getId());
        if (transBusinessLicense != null) authService.deleteTransBusinessLicense(transBusinessLicense);
//        String msg = "尊敬的用户您好，您的组织：%s 已成功解散，组织下的所有员工账户已注销，下次使用时需要重新注册账号！";
//        String fmtMsg = String.format(msg, organize.getOrganizeName());
//        messageRemote.sendPhoneMessage(loginUser.getPhone(), fmtMsg);
    }

    @Override
    public List<Organize> getTruckOrganizeList() {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authorized",true);
        queryWrapper.isNotNull("organize_name");
        return organizeMapper.selectList(queryWrapper);
    }
    @Override
    public PageData<Organize> getTruckOrganizePage(Organize query, Integer page, Integer limit) {
        QueryWrapper<Organize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authorized",true);
        queryWrapper.isNotNull("organize_name");
        QueryUtil.andQueryWrapper(queryWrapper, query);
        return organizeMapper.selectPage(new PageData<>(page, limit), queryWrapper);
    }





}
